package com.ltmall.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ltmall.api.bean.ThClientPlatforms;
import com.ltmall.api.manager.AccountManager;
import com.ltmall.api.redis.RedisUtil;
import com.ltmall.api.util.HttpRequestUtil;
import com.ltmall.api.util.MessageUtil;
import com.ltmall.api.util.RemoteUtil;
import com.ltmall.api.util.WechatUtil;
import com.ltmall.api.wechat.EventDispatcher;
import com.ltmall.api.weixin.util.TemplateMessageUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Controller
public class WechatController {
    static String accessToken = "FmszowbPWdDvpKCrPTEaCU3OO1FSL9iAquNT7_M6c5WPkjh1mrbF99czxA2sF3vv_VopDwyKRbkoJP0EzbPkTTpKL9BdT3l9VHW74CrVvOZupshKqIRTyfZULNpQgQ7KBLWaAEANXI";

    private Logger logger = LogManager.getLogger(WechatController.class);

    private AccountManager accountManager;

    public AccountManager getAccountManager() {
        return accountManager;
    }

    public void setAccountManager(AccountManager accountManager) {
        this.accountManager = accountManager;
    }

    // 验证服务器
    public void verify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        // 微信服务器验证
        if (request.getMethod().equals("GET")) {
            String signature = request.getParameter("signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");

            out = response.getWriter();
            // 判断该请求是否来源于微信
            if (WechatUtil.checkSignature(signature, timestamp, nonce)) {
                out.print(echostr);
            }
        } else { // 接收微信回调信息事件
            try {
                Map<String, String> map = MessageUtil.parseXml(request);
                String msgtype = map.get("MsgType");
                if (MessageUtil.REQ_MESSAGE_TYPE_EVENT.equals(msgtype)) {
                    out.print(EventDispatcher.processEvent(map));
                    if (map.get("Event").equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
                        // 取 EventKey，有就是扫码，没有就是普通
                        String eventKey = "";
                        if (map.containsKey("EventKey")) {
                            eventKey = map.get("EventKey");
                            logger.info("新用户关注，获取EventKey：" + eventKey);
                            if (eventKey.isEmpty() || eventKey.equals("")) {
                                logger.info("新用户名片关注");
                            } else {
                                String qrscene = eventKey.substring(0, 8);
                                logger.info("截取的EventKey前缀：" + qrscene);
                                if (!qrscene.equals("qrscene_")) {
                                    eventKey = "";
                                } else {
                                    eventKey = eventKey.substring(8);
                                    logger.info("新用户扫码关注，获取二维码的参数值：" + eventKey);
                                }
                            }
                        } else {
                            logger.info("新用户普通关注");
                        }

                        String openID = map.get("FromUserName");
                        boolean isExist = checkUserExistsByOpenID(openID);
                        logger.info("新用户关注，用户openid：" + openID + "。这个用户是否已经注册：" + isExist);
                        if (!isExist) { // 不存在，新注册
                            regist(request.getRequestURL().toString(), map.get("FromUserName"),
                                    eventKey);
                        }
                        return;
                    }
                } else {
                    // MsgDispatcher.processMessage(map); //进入消息处理
                    String fromUserN = map.get("FromUserName");
                    String toUserN = map.get("ToUserName");
                    //临时方案
                    if (MessageUtil.REQ_MESSAGE_TYPE_TEXT.equals(msgtype)
                            && ("抽奖".equals(map.get("Content")))) {
                        String content = "http://www.hdplus.cn/hd/normal?mchid=nKqZzCA&temp=1cRv9a6&activity=mC9cqXT&popu=HTDjeD8";
                        StringBuffer buff = new StringBuffer();
                        buff.append("<xml>");
                        buff.append("<ToUserName>").append(fromUserN).append("</ToUserName>");
                        buff.append("<FromUserName>").append(toUserN).append("</FromUserName>");
                        buff.append("<CreateTime>")
                                .append(Long.toString(System.currentTimeMillis() / 1000))
                                .append("</CreateTime>");
                        buff.append("<MsgType><![CDATA[text]]></MsgType>");
                        buff.append("<Content><![CDATA[").append(content).append("]]></Content>");
                        buff.append("</xml>");
                        response.getWriter().print(buff.toString());
                    }
                }
                logger.info("普通操作，不需要给微信返回任何东西");
                out.print("");
            } catch (Exception e) {
                out.print("");
                logger.error(e, e);
            } finally {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            }
        }
    }

    // 微信回调入口
    public void menuUpdate(HttpServletRequest request, HttpServletResponse response) {
        //		// 关于我们
        //		WechatViewButton about = new WechatViewButton();
        //		about.setUrl(
        //				"http://mp.weixin.qq.com/s?__biz=MzIwNjIzNjQwMw==&mid=100000041&idx=1&sn=e4ef4febf3c88b02814435cc864e5bcc&scene=0#wechat_redirect");
        //		about.setName("关于我们");
        //		about.setType("view");
        //
        //		// 招商加盟
        //		WechatViewButton join = new WechatViewButton();
        //		join.setUrl(
        //				"http://mp.weixin.qq.com/s?__biz=MzIwNjIzNjQwMw==&mid=100000037&idx=1&sn=c5406d5b56c3874054c9770234370926&scene=0#wechat_redirect");
        //		join.setName("招商加盟");
        //		join.setType("view");
        //
        //		// 常见问题
        //		WechatViewButton question = new WechatViewButton();
        //		question.setUrl(
        //				"http://mp.weixin.qq.com/s?__biz=MzIwNjIzNjQwMw==&mid=100000039&idx=1&sn=8a007d7e3bd22ecdf797d162113e6167&scene=0#wechat_redirect");
        //		question.setName("常见问题");
        //		question.setType("view");
        //
        //		JSONArray sub_button = new JSONArray();
        //		sub_button.add(about);
        //		sub_button.add(join);
        //		sub_button.add(question);
        //
        //		JSONObject buttonOne = new JSONObject();
        //		buttonOne.put("name", "客服中心");
        //		buttonOne.put("sub_button", sub_button);
        //
        //		// 所有的一级菜单
        //		JSONArray button = new JSONArray();
        //		button.add(buttonOne);
        //
        //		JSONObject menujson = new JSONObject();
        //		menujson.put("button", button);
        //		logger.info("生成的新菜单：" + menujson);
        String menuInfo = request.getParameter("menuInfo");
        if (menuInfo == null) {
            RemoteUtil.response(response, null, -1, "没有提供可用的菜单信息");
        }
        JSONObject menujson = null;
        try {
            menujson = JSON.parseObject(menuInfo);
        } catch (Exception e) {
            RemoteUtil.response(response, null, -1, "提供的菜单信息无法创建");
        }
        logger.info("接收的菜单信息为：" + menujson);
        String accessToken = RedisUtil.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken;
        try {
            String rs = WechatUtil.sendPostBuffer(url, menujson.toString());
            logger.info("创建菜单结果：" + rs);
            RemoteUtil.response(response, null, 1, "菜单创建成功");
        } catch (Exception e) {
            logger.warn("创建菜单失败！！,错误信息：" + e.getMessage());
            RemoteUtil.response(response, null, -1, "菜单创建失败");
        }
    }

    public void testMenuUpdate(HttpServletRequest request, HttpServletResponse response) {
        String menuInfo = request.getParameter("menuInfo");
        if (menuInfo == null) {
            RemoteUtil.response(response, null, -1, "没有提供可用的菜单信息");
        }
        JSONObject menujson = null;
        try {
            menujson = JSON.parseObject(menuInfo);
        } catch (Exception e) {
            RemoteUtil.response(response, null, -1, "提供的菜单信息无法创建");
        }
        logger.info("接收的菜单信息为：" + menujson);
        String accessToken = RedisUtil.getTestAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken;
        try {
            String rs = WechatUtil.sendPostBuffer(url, menujson.toString());
            logger.info("创建菜单结果：" + rs);
            RemoteUtil.response(response, null, 1, "菜单创建成功");
        } catch (Exception e) {
            logger.warn("创建菜单失败！！,错误信息：" + e.getMessage());
            RemoteUtil.response(response, null, -1, "菜单创建失败");
        }
    }

    public void menuGet(HttpServletRequest request, HttpServletResponse response) {
        String accessToken = RedisUtil.getAccessToken();

        Map<String, String> accessTokenMap = new HashMap<String, String>();
        accessTokenMap.put("access_token", accessToken);
        String result = "";
        try {
            result = WechatUtil.sendGet("https://api.weixin.qq.com/cgi-bin/menu/get",
                    accessTokenMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        RemoteUtil.response(response, jsonObject, 1, "success");
    }

    public void testMenuGet(HttpServletRequest request, HttpServletResponse response) {
        String accessToken = RedisUtil.getTestAccessToken();

        Map<String, String> accessTokenMap = new HashMap<String, String>();
        accessTokenMap.put("access_token", accessToken);
        String result = "";
        try {
            result = WechatUtil.sendGet("https://api.weixin.qq.com/cgi-bin/menu/get",
                    accessTokenMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        RemoteUtil.response(response, jsonObject, 1, "success");
    }

    // 检查openid是否注册
    private boolean checkUserExistsByOpenID(String openID) {
        ThClientPlatforms info = accountManager.checkUserExistByOpenID(openID);
        if (info != null) {
            return true;
        } else {
            return false;
        }
    }

    // 注册新用户
    private boolean regist(String registURL, String openid, String subUnderwriterId) {
        String accessToken = RedisUtil.getAccessToken();
        JSONObject userInfoJson = HttpRequestUtil.sendGet(
                "https://api.weixin.qq.com/cgi-bin/user/info", "access_token=" + accessToken
                        + "&openid=" + openid + "&lang=zh_CN");
        if (userInfoJson.containsKey("errcode")) {
            int errcode = (Integer) userInfoJson.get("errcode");
            if (errcode > 0) {
                logger.warn("注册验证openId错误：" + errcode);
                return false;
            }
        }
        logger.info("注册获取到的用户信息为：" + userInfoJson);
        String name = userInfoJson.get("nickname").toString();
        String photo = userInfoJson.get("headimgurl").toString();
        String sex = userInfoJson.get("sex").toString();
        logger.info("注册用户：" + name);
        logger.info("注册头像：" + photo);
        logger.info("注册性别：" + sex);
        registURL = registURL.replace("wechat", "account");
        logger.info("注册地址：" + registURL);
        JSONObject registResultJson = HttpRequestUtil.sendPost(registURL,
                "method=registerByPlatform" + "&name=" + name + "&photo=" + photo + "&sex=" + sex
                        + "&openId=" + openid + "&subUnderwriterId=" + subUnderwriterId);
        logger.info("注册返回结果：" + registResultJson);

        if (registResultJson == null || !registResultJson.containsKey("code")
                || !registResultJson.containsKey("data")) {
            return false;
        }

        if (registResultJson.get("code").equals("-1")) {
            return false;
        }

        // 进行新注册用户模板消息推送
        int userId = (Integer) ((JSONObject) registResultJson.get("data"))
                .get("userID");
        JSONObject userList = HttpRequestUtil.sendGet(
                "https://api.weixin.qq.com/cgi-bin/user/get",
                "access_token=" + RedisUtil.getAccessToken());
        if (userList.containsKey("errcode")) {
            return false;
        }

        int userCount = 0;
        if (userList.containsKey("total")) {
            userCount = userList.getInteger("total");
        }

        TemplateMessageUtil.sendRegisterSuccessMessage(openid, userId, userCount);

        // 进行新粉丝加入模板消息推送
        if (!subUnderwriterId.equals("")) {
            ThClientPlatforms clientPlatforms = accountManager.getClientPlatformByUserId(Integer
                    .parseInt(subUnderwriterId));
            TemplateMessageUtil.sendHasNewFansMessage(clientPlatforms.getOpenId(), name);
        }

        return true;
    }
}
